package com.wiringweb.servlet;

import com.wiringweb.exceptions.WiringWebException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;

/**
 * @author Dmitry
 */
public abstract class BaseWiringWebController {

    private WiringRequestProcessor wiringRequestProcessor;

    public void setWiringRequestProcessor(WiringRequestProcessor wiringRequestProcessor) {
        this.wiringRequestProcessor = wiringRequestProcessor;
    }

    protected BaseWiringWebController addRequestParameter(String key, Object value) {
        if (key.equals("session")) {
            throw new WiringWebException("Cannot add request parameter 'session' because it is reserved word");
        }
        wiringRequestProcessor.getRequest().setAttribute(key, value);
        return this;
    }

    protected Object getRequestParameter(String key) {
        return wiringRequestProcessor.getRequest().getAttribute(key);
    }

    protected BaseWiringWebController removeRequestParameter(String key) {
        wiringRequestProcessor.getRequest().setAttribute(key, null);
        wiringRequestProcessor.getRequest().removeAttribute(key);
        return this;
    }

    protected BaseWiringWebController removeSessionParameter(String key) {
        HttpSession session = wiringRequestProcessor.getRequest().getSession(true);
        Map<String, Object> data = (Map<String, Object>) session.getAttribute("data");
        if (data == null) {
            return this;
        }
        data.remove(key);
        return this;
    }

    protected BaseWiringWebController addSessionParameter(String key, Object value) {
        HttpSession session = wiringRequestProcessor.getRequest().getSession(true);
        Map<String, Object> data = (Map<String, Object>) session.getAttribute("data");
        if (data == null) {
            data = new HashMap<String, Object>();
            session.setAttribute("data", data);
        }

        data.put(key, value);
        return this;
    }

    protected Object getSessionParameter(String key) {
        HttpSession session = wiringRequestProcessor.getRequest().getSession(false);
        if (session == null) {
            return null;
        }

        Map<String, Object> data = (Map<String, Object>) session.getAttribute("data");
        if (data == null) {
            return null;
        }
        return data.get(key);
    }
}
